package com.futong.cloud.utils;

import com.alibaba.fastjson.JSONPath;
import com.futong.cloud.action.ActionContext;
import com.futong.cloud.action.ActionModel;
import com.futong.cloud.dao.entity.ActionFiled;
import org.apache.commons.lang.StringUtils;

import java.util.Optional;

public class ContextUtils {

    public static String getValueByFiledName(ActionContext context, String filed){
        Optional<ActionModel.ActionFiledModel> any = context.getActionModel().getFileds().stream().filter(t -> t.getFiled().equalsIgnoreCase(filed)).findAny();
        if(!any.isPresent())return null;
        return JsonUtils.evalStr(context,any.get().getContextPath());
    }
    public static String getValueStr(ActionContext context, ActionFiled filed){
        if(StringUtils.isEmpty(filed.getContextPath()))return null;
        return JsonUtils.evalStr(context,filed.getContextPath());
    }
    public static String getValueStr(ActionContext context, String path){
        if(StringUtils.isEmpty(path))return null;
        return JsonUtils.evalStr(context,path);
    }
    public static Object getValue(ActionContext context,String path){
        if(StringUtils.isEmpty(path))return null;
        return JsonUtils.eval(context,path);
    }
    public static void setValueByScope(ActionContext context,Object obj,String scope){
        context.getActionModel().getFileds().stream()
                .filter(t->scope.equalsIgnoreCase(t.getScope())&& StringUtils.isNotEmpty(t.getCloudPath()))
                .forEach(t->{
                    JSONPath.set(obj,t.getCloudPath(),JsonUtils.evalStr(context,t.getContextPath()));
                });
    }
}
